{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用 Monte-Carlo 方法求解 0-1 背包问题\n",
    "\n",
    "算法步骤：\n",
    "1. 初始化大的正整数 N.\n",
    "2. 随机产生 N 条决策路径.\n",
    "3. 计算每条路径得到价值.\n",
    "4. 选取最大的价值作为近似最优解."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 基本设置\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "15 70 [4, 13, 2, 18, 3, 3, 4, 16, 8, 17, 5, 1, 20, 2, 14] [21, 1, 3, 11, 13, 16, 16, 20, 21, 11, 15, 7, 10, 3, 19]\n"
     ]
    }
   ],
   "source": [
    "# 数据读取\n",
    "import re\n",
    "def LoadData(path):\n",
    "    '''\n",
    "    数据读取。\n",
    "    Input:\n",
    "    - path: 数据路径.\n",
    "    \n",
    "    Return:\n",
    "    - cache: a list contains (n,c,w,v)\n",
    "    '''\n",
    "    cache = []\n",
    "    with open(path,'r') as f:  \n",
    "         for i in range(4):\n",
    "            x = re.findall(r'\\d+',f.readline())\n",
    "            x = [int(i) for i in x]\n",
    "            cache.append(x)\n",
    "    return cache\n",
    "    \n",
    "path = 'test3.txt'\n",
    "n,c,w,v = LoadData(path)\n",
    "n = n[0]\n",
    "c = c[0]\n",
    "print(n,c,w,v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def GenRandomSeq(n,N):\n",
    "    '''\n",
    "    生成 N 个长度 n 的随机二进制序列.\n",
    "    Input:\n",
    "    - n: 长度.\n",
    "    - N: 路径数.\n",
    "    \n",
    "    Return:\n",
    "    - seqs: 序列.\n",
    "    '''\n",
    "    # 固定种子\n",
    "    np.random.seed(231)\n",
    "    seqs = []\n",
    "    numbers = np.random.randint(1,2**n,size=(N)).tolist()\n",
    "    for i in numbers:\n",
    "        x = list('{i:0>{n}b}'.format(i=i, n=n))\n",
    "        x = np.array([int(i) for i in x]) \n",
    "        seqs.append(x)\n",
    "    return seqs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def Evaluate(w,v,c,seq):\n",
    "    '''\n",
    "    计算路径的价值.\n",
    "    Input:\n",
    "    - w: 重量.\n",
    "    - v: 价值.\n",
    "    - seq: 序列.\n",
    "    \n",
    "    Return:\n",
    "    - value: 路径的价值.\n",
    "    '''\n",
    "    weight = 0\n",
    "    value = 0\n",
    "    for i in range(len(seq)):\n",
    "        if seq[i] == 1:\n",
    "            weight = weight + w[i]\n",
    "            value = value + v[i]\n",
    "    if weight > c:\n",
    "        # 不可行\n",
    "        return 0\n",
    "    return value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "154"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def Monte_Carlo(n,c,w,v,N=1000):\n",
    "    '''\n",
    "    使用 Monte-Carlo 方法求解 0-1 背包问题的最优解.\n",
    "    Input:\n",
    "    - n: 物品数量.\n",
    "    - w: 物品重量.\n",
    "    - c: 背包容量.\n",
    "    - v: 物品价值.\n",
    "    \n",
    "    Return:\n",
    "    - value: 最优价值.\n",
    "    '''\n",
    "    # 生成 N 条路径\n",
    "    seqs = GenRandomSeq(n,N)\n",
    "    \n",
    "    # 计算每条路径的价值\n",
    "    values = []\n",
    "    for seq in seqs:\n",
    "        values.append(Evaluate(w,v,c,seq))\n",
    "        \n",
    "    # 近似\n",
    "    value = max(values)\n",
    "    \n",
    "    return value\n",
    "Monte_Carlo(n,c,w,v,N=100000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch",
   "language": "python",
   "name": "torch"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
